package com.example.kddemo.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 熔断器demo
 */
@Controller
@CrossOrigin("*")
@RequestMapping(value = "/")
public class HystrixController {

    @RequestMapping(value = "/hello/{str}")
    @HystrixCommand(

            groupKey = "hello_service_group_key",

            threadPoolKey = "hello_service_tread_pool_key",

            fallbackMethod = "fallback_hello",

            commandProperties = {

                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "10000"),

                    //是否开启熔断器
                    @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),

                    //请求的失败数目超过这个之后，就会打开熔断器
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "5"),

                    //熔断器工作时间，默认5秒，超过这个时间便会放流量进去
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"),
                    //出错率超过50%，启动熔断器，默认50%
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
            },
            //以下这些值，在分组的情况下有效
            threadPoolProperties = {

                    //核心线程数
                    @HystrixProperty(name = "coreSize", value = "2"),
                    //超过队列的个数会直接失败
                    @HystrixProperty(name = "maxQueueSize", value = "5"),
                    //队列小于最大值，拒绝请求
                    @HystrixProperty(name = "queueSizeRejectionThreshold", value = "2")


            }
    )

    @ResponseBody
    public Object hello(@PathVariable("str") String str) {
        return "服务2" + str;
    }

    public Object fallback_hello(String str) {

        return "2服务出现错误" + str;
    }

}
